package com.fieldchain.ex.fa100.ui.trade.fragment;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fieldchain.ex.fa100.R;
import com.fieldchain.ex.fa100.access.Constant;
import com.fieldchain.ex.fa100.bean.DemicBean;
import com.fieldchain.ex.fa100.bean.TradBean;
import com.fieldchain.ex.fa100.inter.IntegerCallBack;
import com.fieldchain.ex.fa100.inter.MyValueListener;
import com.fieldchain.ex.fa100.inter.StringCallBack;
import com.fieldchain.ex.fa100.inter.TradTextLsitener;
import com.fieldchain.ex.fa100.inter.TradeCallBack;
import com.fieldchain.ex.fa100.ui.personal.activity.LoginActivity;
import com.fieldchain.ex.fa100.ui.trade.adapter.TradBuyAdapter;
import com.fieldchain.ex.fa100.ui.trade.adapter.TradNewAdapter;
import com.fieldchain.ex.fa100.ui.trade.adapter.TradSellAdapter;
import com.fieldchain.ex.fa100.ui.trade.string.TradTextWtcher;
import com.fieldchain.ex.fa100.utils.animator.AnimationUtils;
import com.fieldchain.ex.fa100.utils.common.InputCount;
import com.fieldchain.ex.fa100.utils.net.access.HttpRequest;
import com.fieldchain.ex.fa100.utils.net.access.WebSocketRequet;
import com.fieldchain.ex.fa100.utils.net.common.UpdateUser;
import com.fieldchain.ex.fa100.utils.net.modle.BeanRequest;
import com.fieldchain.ex.fa100.utils.net.modle.StringRequest;
import com.fieldchain.ex.fa100.utils.screen.Dputils;
import com.fieldchain.ex.fa100.utils.screen.MyToast;
import com.fieldchain.ex.fa100.utils.share.ShareManager;
import com.fieldchain.ex.fa100.utils.string.NumberFormate;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/20
 */
public class TradBuyFragment extends BaseTradFragment implements View.OnClickListener, AppBarLayout.OnOffsetChangedListener {

    @BindView(R.id.appbarLayout)
    AppBarLayout appbarLayout;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.rb_all)
    RadioButton rbAll;
    @BindView(R.id.rb_buy)
    RadioButton rbBuy;
    @BindView(R.id.rb_sell)
    RadioButton rbSell;
    @BindView(R.id.rb_usd)
    RadioButton rbUsd;
    @BindView(R.id.rb_cny)
    RadioButton rbCny;
    @BindView(R.id.tv_companym2_0)
    TextView tvCompanym20;
    @BindView(R.id.rv_sell)
    RecyclerView rvSell;
    @BindView(R.id.lin_price)
    LinearLayout linPrice;
    @BindView(R.id.tv_num1)
    TextView tvNum1;
    @BindView(R.id.tv_companym2_1)
    TextView tvCompanym21;
    @BindView(R.id.tv_num2)
    TextView tvNum2;
    @BindView(R.id.tv_companym3_0)
    TextView tvCompanym30;
    @BindView(R.id.rv_buy)
    RecyclerView rvBuy;
    @BindView(R.id.rea_price)
    RelativeLayout reaPrice;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.tv_companym2_2)
    TextView tvCompanym22;
    @BindView(R.id.tv_companym4_0)
    TextView tvCompanym40;
    @BindView(R.id.tv_num3)
    TextView tvNum3;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.tv_companym1_0)
    TextView tvCompanym10;
    @BindView(R.id.rg_per)
    RadioGroup rgPer;
    @BindView(R.id.rd_per0)
    RadioButton rdPer0;
    @BindView(R.id.rd_per1)
    RadioButton rdPer1;
    @BindView(R.id.rd_per2)
    RadioButton rdPer2;
    @BindView(R.id.rd_per3)
    RadioButton rdPer3;
    @BindView(R.id.tv_num4)
    TextView tvNum4;
    @BindView(R.id.tv_companym2_3)
    TextView tvCompanym23;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_companym2_4)
    TextView tvCompanym24;
    @BindView(R.id.tv_num5)
    TextView tvNum5;
    @BindView(R.id.tv_companym1_1)
    TextView tvCompanym11;
    @BindView(R.id.tv_num6)
    TextView tvNum6;
    @BindView(R.id.rv_new)
    RecyclerView rvNew;
    @BindView(R.id.rea_new1)
    RelativeLayout reaNew1;
    @BindView(R.id.rea_bot1)
    RelativeLayout reaBot1;
    @BindView(R.id.tv_companym2_a)
    TextView tvCompanym2A;

    private int index, height, top, rvA, rvO;
    private int[][] a = new int[3][4];

    private double p0 = 0, p1 = 0, p = 0;
    private int moneyType = 1;
    private double price = 0, priceNew = 0;
    private TradBuyAdapter buyAdpter;
    private TradSellAdapter sellAdapter;
    private TradNewAdapter newAdapter;
    private WebSocketRequet webSocket;

    private Drawable drawable;
    private GradientDrawable redBac, greenBac;
    private boolean isRedAnimator = true;

    private ValueAnimator animation;
    private TradTextWtcher watcher;
    private double m1, m2;
    private int length = 4;
    private int numLength = 4, priceLength = 4;
    private String loginStr = "登录/注册";

    private boolean needPer = false;

    @Override
    protected void findView() {
        appbarLayout.addOnOffsetChangedListener(this);
    }

    @Override
    protected void setValue() {
        needProgress = false;
        webSocket = new WebSocketRequet();
        initRv();
        initRadio();
        setOnClick();
        initAn();
        initWatcher();
    }

    private void initWatcher() {
        watcher = new TradTextWtcher(etPrice, etNum, new TradTextLsitener() {
            @Override
            public void priceAbout(double pri) {
                price = pri;
                tvNum3.setText(NumberFormate.m5(price * p));
            }

            @Override
            public void amount(double amount) {
                if (!needPer) {
                    rgPer.clearCheck();
                } else {
                    needPer = false;
                }
                if (amount > m1) {
                    tvNum4.setText(NumberFormate.m5(m1));
                    etNum.setText(NumberFormate.m(m1 / price + "", numLength, false));
                    if (m1 == 0) {
                        MyToast.show("余额不足");
                    }
                } else {
                    tvNum4.setText(NumberFormate.m5(amount));
                }
            }
        });
    }

    private void initAn() {
        drawable = reaPrice.getBackground();
        redBac = new GradientDrawable();
        redBac.setShape(GradientDrawable.RECTANGLE);
        redBac.setCornerRadius(Dputils.dp2px(6));
        redBac.setStroke(2, Color.parseColor("#DC3950"));

        greenBac = new GradientDrawable();
        greenBac.setShape(GradientDrawable.RECTANGLE);
        greenBac.setCornerRadius(Dputils.dp2px(6));
        greenBac.setStroke(2, Color.parseColor("#17AE5D"));

        animation = ValueAnimator.ofInt(0, 255);
        animation.setDuration(550);
        animation.setRepeatCount(2);
//        animation.setInterpolator(new BounceInterpolator());
        animation.setInterpolator(new AccelerateInterpolator(1));
        AnimationUtils.setListener(animation, new MyValueListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (isRedAnimator) {
                    redBac.setAlpha((Integer) (animation.getAnimatedValue()));
                    reaPrice.setBackground(redBac);
                } else {
                    greenBac.setAlpha((Integer) (animation.getAnimatedValue()));
                    reaPrice.setBackground(greenBac);
                }
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                reaPrice.setBackground(drawable);
            }
        });

    }


    @Override
    public void onResume() {
        super.onResume();
        if (!isFirst) {
            startWebSocket();
        }
        UpdateUser.update(new IntegerCallBack() {
            @Override
            public void index(int pos) {
                if (pos == 200) {
                    if (!tvSure.getText().toString().equals("立即买入")) {
                        tvSure.setText("立即买入");
                    }
                } else if (pos == 403) {
                    if (!tvSure.getText().toString().equals(loginStr)) {
                        tvSure.setText(loginStr);
                    }
                }
            }
        });
        isFirst = false;
    }

    @Override
    public void onPause() {
        super.onPause();
        webSocket.close();
    }

    public void startWebSocket() {
        HashMap map = new HashMap();
        map.put("event", "dealRecord");
        map.put("market", market.toLowerCase());
        map.put("type", "phone");
        String send = new Gson().toJson(map);
        webSocket.start(Constant.webSocket, send, new StringCallBack() {
            @Override
            public void message(String msg) {
                if (msg.contains("dealRecord")) {
                    TradBean bean = new Gson().fromJson(msg, TradBean.class);
                    setWebData(bean);
                }
            }
        });
    }

    public void setWebData(TradBean bean) {
        if (mContext == null) {
            webSocket.close();
            return;
        }
        p0 = bean.getPriceSort().getDealRatioUsd();
        p1 = bean.getPriceSort().getDealRatioCny();
        if (moneyType == 0) {
            p = p0;
        } else {
            p = p1;
        }
        tvNum3.setText(NumberFormate.m5(price * p));
        List<List<Double>> list1 = bean.getPriceSort().getSellSort();
        List<List<Double>> list2 = bean.getPriceSort().getBuySort();
        List<TradBean.DealRecordBean> list3 = bean.getDealRecord();
        sellAdapter.setData(list1, priceLength, numLength);
        buyAdpter.setData(list2, priceLength, numLength);
        newAdapter.setData(list3, priceLength, numLength);
        if (list3.size() > 1) {
            rvSell.smoothScrollToPosition(list3.size() - 1);
            priceNew = list3.get(0).getPrice();
            tvNum6.setText(NumberFormate.m2(m1 / priceNew + ""));
            tvNum2.setText(NumberFormate.m2(priceNew * p));
            tvNum1.setText(NumberFormate.m2(priceNew));
        }
    }

    private void initRadio() {
        setOnChecked(rbAll, 0, 0);
        setOnChecked(rbSell, 0, 1);
        setOnChecked(rbBuy, 0, 2);

        setOnChecked(rbUsd, 1, 0);
        setOnChecked(rbCny, 1, 1);

        setOnChecked(rdPer0, 2, 0);
        setOnChecked(rdPer1, 2, 1);
        setOnChecked(rdPer2, 2, 2);
        setOnChecked(rdPer3, 2, 3);
    }

    public void setOnChecked(RadioButton rb, final int type, final int index) {
        rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    a[type][index] = 1;
                    if (type == 0) {
                        cRv(index);
                    } else if (type == 1) {
                        moneyType = index;
                        cMoey(index);
                    } else if (type == 2) {
                        cPer(index);
                    }
                }
            }
        });
    }

    public void cPer(int index) {
        if (price == 0) {
            needPer = false;
            if (m1 == 0) {
                MyToast.show("资金不足");
            } else {
                MyToast.show("请输入价格");
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    rgPer.clearCheck();
                }
            }, 10);

            return;
        } else {
            needPer = true;
            double num = (index + 1) * 0.25 * m1 / price;
            String text = NumberFormate.m(num + "", numLength, false);
            etNum.setText(text);
        }
    }

    private void cMoey(int index) {
        if (index == 0) {
            tvCompanym30.setText("USD");
            tvCompanym40.setText("＄");
            p = p0;
        } else if (index == 1) {
            tvCompanym30.setText("CNY");
            tvCompanym40.setText("¥");
            p = p1;
        }
        tvNum3.setText(NumberFormate.m5(price * p));
        tvNum2.setText(NumberFormate.m2(priceNew * p));
    }

    private void cRv(int index) {
        if (index == 0) {
            linPrice.setVisibility(View.VISIBLE);
            rvBuy.setVisibility(View.VISIBLE);
            rvSell.setVisibility(View.VISIBLE);
            setRvParams(rvBuy, 0);
            setRvParams(rvSell, 0);
        } else if (index == 1) {
            rvBuy.setVisibility(View.GONE);
            rvSell.setVisibility(View.VISIBLE);
            linPrice.setVisibility(View.GONE);
            setRvParams(rvSell, 1);
        } else if (index == 2) {
            rvBuy.setVisibility(View.VISIBLE);
            rvSell.setVisibility(View.GONE);
            linPrice.setVisibility(View.GONE);
            setRvParams(rvBuy, 1);
        }
    }

    public void setOnClick() {
        reaNew1.setOnClickListener(this);
        tvSure.setOnClickListener(this);
        reaBot1.setOnClickListener(this);
    }


    @Override
    public int getLayout() {
        return R.layout.fragment_trad_buy;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rea_bot1:
                if (checkbox.isChecked()) {
                    appbarLayout.setExpanded(true);
                } else {
                    appbarLayout.setExpanded(false);
                }
//                scroll.smoothScrollTo(0, rvNew.getBottom());
                break;
            case R.id.rea_new1:
//                scroll.smoothScrollTo(0, reaBot.getBottom() - index);
                break;
            case R.id.tv_sure:
                if (tvSure.getText().toString().equals(loginStr)) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    upload();
                }
                break;
        }
    }


    public void initRv() {
        index = Dputils.dp2px(48);
        height = ShareManager.getInstance().getHeight() - Dputils.dp2px(123);
        rvA = height - Dputils.dp2px(144);
        rvO = height - Dputils.dp2px(109);
        setRvParams(rvBuy, 0);
        setRvParams(rvSell, 0);

        ViewGroup.LayoutParams rvParms = rvNew.getLayoutParams();
        rvParms.height = ShareManager.getInstance().getHeight() - Dputils.dp2px(208);
        rvNew.setLayoutParams(rvParms);

        rvSell.setLayoutManager(new LinearLayoutManager(mContext));
        rvBuy.setLayoutManager(new LinearLayoutManager(mContext));
        rvNew.setLayoutManager(new LinearLayoutManager(mContext));

        buyAdpter = new TradBuyAdapter(mContext);
        sellAdapter = new TradSellAdapter(mContext);
        newAdapter = new TradNewAdapter(mContext);


        rvBuy.setAdapter(buyAdpter);
        rvSell.setAdapter(sellAdapter);
        rvNew.setAdapter(newAdapter);

        buyAdpter.setCallBack(new TradeCallBack() {
            @Override
            public void onClick(int type, int position, double value) {
                if (animation.isRunning()) {
                    animation.cancel();
                }
                isRedAnimator = true;
                animation.start();
                etPrice.setText(NumberFormate.m(value, priceLength));
            }
        });
        sellAdapter.setCallBack(new TradeCallBack() {
            @Override
            public void onClick(int type, int position, double value) {
                if (animation.isRunning()) {
                    animation.cancel();
                }
                isRedAnimator = false;
                animation.start();
                etPrice.setText(NumberFormate.m(value, priceLength));
            }
        });

        newAdapter.setCallBack(new TradeCallBack() {
            @Override
            public void onClick(int type, int position, double value) {
                if (animation.isRunning()) {
                    animation.cancel();
                }
                isRedAnimator = (type == 1);
                animation.start();
                appbarLayout.setExpanded(false);
//                scroll.smoothScrollTo(0, reaBot.getBottom() - index);
                etPrice.setText(NumberFormate.m(value, priceLength));
            }
        });
    }

    public void setRvParams(RecyclerView rv, int type) {
        ViewGroup.LayoutParams params = rv.getLayoutParams();
        int h = type == 0 ? rvA / 2 : rvO;
        params.height = h;
        rv.setLayoutParams(params);
    }

    @Override
    public void setCompany() {
        tvCompanym20.setText(coin);
        tvCompanym21.setText(coin);
        tvCompanym22.setText(coin);
        tvCompanym23.setText(coin);
        tvCompanym24.setText(coin);
        tvCompanym2A.setText(coin);
        tvCompanym10.setText(company);
        tvCompanym11.setText(company);
        getDemicLength();
        getMoney();
        startWebSocket();
    }


    public void upload() {

        String num = etNum.getText().toString();
        String pwd = etPwd.getText().toString();
        if (price == 0) {
            MyToast.show("请输入价格");
            return;
        }
        if (num.length() == 0) {
            MyToast.show("请输入交易数量");
            return;
        }
        if (pwd.length() == 0) {
            MyToast.show("请输入交易密码");
            return;
        }
        tvSure.setEnabled(false);
        HashMap map = new HashMap();
        map.put("market", market.toLowerCase());
        map.put("dealType", 1 + "");
        map.put("price", price + "");
        map.put("entrustNumber", num);
        String json = new Gson().toJson(map);
        String url = Constant.trad + "?password=" + pwd;
        HttpRequest.getInstance().postRequest(json, url, new StringRequest() {
            @Override
            public void onSucess(String str, int code, String msg) {
                tvSure.setEnabled(true);
                if (code == 200) {
                    setEmpty();
//                    EventBus.getDefault().post(new TradEvent(2));
                }
                MyToast.show(msg);
            }

            @Override
            public void onFaild(Exception e) {
                tvSure.setEnabled(true);
            }
        });
    }

    public void setEmpty() {
        price = 0.00;
        priceNew = 0.00;
        etNum.setText("");
        etPrice.setText("");
        etPwd.setText("");
        tvNum3.setText("0.00");
        tvNum4.setText("0.00");
        getMoney();
        ((RadioGroup) rdPer0.getParent()).clearCheck();
    }

    public void getMoney() {
        HashMap map = new HashMap();
        map.put("market", market);
        HttpRequest.getInstance().getRequest(map, Constant.pMkCoin, new BeanRequest<HashMap<String, String>>() {
            @Override
            public void onSucess(HashMap<String, String> map, int code, String msg) {
                if (code == 200) {
                    if (map != null && map.size() == 2) {
                        m1 = Double.parseDouble(map.get(coin.toUpperCase()));
                        tvNum5.setText(NumberFormate.m3(m1));
//                        m1=DoubleParse.parse(NumberFormate.m2(map.get(coin.toUpperCase())));
//                        tvNum5.setText(m1+"");
                    }
                }
            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }


    public void getDemicLength() {
        etNum.setText("");
        etPrice.setText("");
        HashMap map = new HashMap();
        map.put("market", market.toLowerCase());
        HttpRequest.getInstance().getRequest(map, Constant.demicRequest, new BeanRequest<DemicBean>() {
            @Override
            public void onSucess(DemicBean demicBean, int code, String msg) {
                if (code == 200) {
                    numLength = demicBean.getNumberPrecision();
                    priceLength = demicBean.getPricePrecision();
                    etNum.setFilters(new InputFilter[]{new InputCount(numLength)});
                    etPrice.setFilters(new InputFilter[]{new InputCount(demicBean.getPricePrecision())});
                }
            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }

    @Override
    public void loginShow() {
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset == 0) {
            checkbox.setChecked(false);
        } else {
            checkbox.setChecked(true);
        }
    }
}
